(function () {

    var startId = $("#objectId").attr("value");
    window.startFields = JSON.parse($("#columns").attr("value"));
    var tableName = $("#tableName").attr("value");
    var dsId = $("#dsId").attr("value");
    var objectChname = $("#objectChname").attr("value");
    var isEnglish = true;
    
    var toolbar = new joint.ui.Toolbar({   //头部控制模块

        tools: [
            {
                type: 'button',
                name: 'undo',
                group: 'undo-redo',
                attrs: {
                    button: {
                        'id':'btn-undo',
                        'data-tooltip': '撤销',
                        'data-tooltip-position': 'top',
                        'data-tooltip-position-selector': '.toolbar-container'
                    }
                }
            },
            {
                type: 'button',
                name: 'redo',
                group: 'undo-redo',
                attrs: {
                    button: {
                        'id':'btn-redo',
                        'data-tooltip': '返回',
                        'data-tooltip-position': 'top',
                        'data-tooltip-position-selector': '.toolbar-container'
                    }
                }
            },

            {
                type: 'button',
                group: 'layout',
                name: 'layout',
                attrs: {
                    button: {
                        id: 'btn-layout',
                        'data-tooltip': '自动布局',
                        'data-tooltip-position': 'top',
                        'data-tooltip-position-selector': '.toolbar-container'
                    }
                }
            },
            {
                type: 'zoom-to-fit',
                name: 'zoom-to-fit',
                group: 'zoom',
                attrs: {
                    button: {
                        'data-tooltip': '自适应缩放',
                        'data-tooltip-position': 'top',
                        'data-tooltip-position-selector': '.toolbar-container'
                    }
                }
            },
            {
                type: 'label',
                name: 'zoom-slider-label',
                group: 'zoom',
                text: 'Zoom:'
            },
            {
                type: 'zoom-slider',
                name: 'zoom-slider',
                group: 'zoom'
            },
            
            {
                type: 'toggle',
                name: 'toggle',
                group: 'last',
            },

        ],
        references: {
            paperScroller: paperScroller,
        }
    });

    $('#app').prepend(toolbar.render().el);
    
    
    //中英文切换
    toolbar.on('toggle:change', function(value, event) {

        $.each(graph.getElements(),function(i,v){
        	var cell = v;
        	var view = paper.findViewByModel(v);
        	var currentColumn = view.$el.find(".columnName");
        	 	  	 
        	 //如果是中文
        	 if(value === true){
        		 isEnglish = false;
        		 cell.attributes.attrs.isEnglish = false; //是中文
        		 view.$el.find("tspan").text(cell.attributes.attrs.objectChname);
        		 $.each(currentColumn, function (i, v) {
            		 var columnchname = $(this).attr("data-columnchname");
                  
                     $(this).text(columnchname);

                 })
        	 }else {
        		 isEnglish = true;
        		 cell.attributes.attrs.isEnglish = true; //是英文
        		 view.$el.find("tspan").text(cell.attributes.attrs.tableName);
        		 
        		 $.each(currentColumn, function (i, v) {
            		 var columnchname = $(this).attr("data-columnname");
            	
                     $(this).text(columnchname);

                 })
        	 }
        	 
        	 cell.attributes.attrs.div.html = view.$el.find('.content').html();
        })
        var promptMsg = "";
    	value=== true?promptMsg="已切换为中文":promptMsg = "已切换为英文";
        layer.msg(promptMsg,{time:1500})
    });
    
    var objData = $.map(startFields,function(v,i){
    	return {
    		columnName : v.field,
    		value : v.value
    	}
    });
    var objColumns =  $.map(startFields,function(v,i){
    	return {
    		columnName : v.field,
    		columnChname : v.columnChname,
    		pk : true
    	}
    });
    var obj = {
        "objectId": startId,
        "dsId": dsId,
        "tableName": tableName,
        "objectChname": objectChname,
        "isOpen" : {isRightOpen: "",isLeftOpen : ""},
        "data":[objData],
        "columns":objColumns
    };
  //  console.log(obj)
  
    //点击切换记录(翻页)
    $('.paperBox').on('click', '.content .totalLog a', function () {

        var id = $(this).parents('.joint-cell').attr('model-id');       //得到当前的id
        var cell = graph.getCell(id);                                   //model
        var view = paper.findViewByModel(cell);                         //view

        var logNumber = cell.attributes.attrs.logNumber;        //全部记录条数
        var currentNum = cell.attributes.attrs.currentLogNum;  //当前的记录条数
        var columnValueArray = view.$el.find(".columnValue");     //当前字段值数组(view)
        var logs = cell.attributes.attrs.logs;              //所有的字段值数组

       if($(this).hasClass("prevTolog")){ //点击上一页

            if(currentNum-1 >= 1){
                cell.attributes.attrs.currentLogNum = currentNum-1;
            }else {
                return;
            }

       }else {  //点击下一页

           if(currentNum+1 <= logNumber) {
               cell.attributes.attrs.currentLogNum = currentNum+1;
           }else {
               return;
           }

       }
        //切换字段值
       var currentLog = logs[cell.attributes.attrs.currentLogNum -1]; //当前记录
       var where = cell.attributes.attrs.where;         //where参数
        $.each(currentLog,function (i, v) { //遍历当前记录
            var that = v;
            $.each(columnValueArray,function (i, v) {  //遍历当前字段值数组(view)
                if(that.columnName === $(v).attr("data-columnname")){
                    $(v).text(that.value)
                }
            });

            $.each(where,function (i,v) {       //遍历where参数
                if(that.columnName === v.srcColumnName){
                   v.value =  that.value
                }
            });
        });

       $(".layui-laypage-curr").text(cell.attributes.attrs.currentLogNum); //页码切换

        cell.attributes.attrs.where  = where; //表保存的where参数切换
        cell.attributes.attrs[".content"].html = view.$el.find('.content').html(); //model中数据更新

    });

    //单击元素
    paper.on('cell:pointerclick', function (cellView) {
        console.log(cellView.model);
        //halo组件初始化
        var halo = new joint.ui.Halo({theme: 'modern', cellView: cellView});
        //link没有halo组件
        if (cellView.model instanceof joint.shapes.app.Link) return;
        halo.removeHandle('clone');
        halo.removeHandle('fork');
        halo.removeHandle('unlink');
        halo.removeHandle('rotate');
        halo.removeHandle('link');
        halo.removeHandle('remove');
        halo.render();
        if (cellView.model.attributes.type === "bpmn.Choreography") {  //如果是展开表数据
            //判断是否向左展开
            if(cellView.model.attributes.attrs.isLeftOpen) {
                halo.addHandle({ name: 'myaction', position: 'nw', icon: '/assets/custom/draw/img/wancheng.svg' });
            }else {
                //自定义向左加载表
                halo.addHandle({
                    name: 'addTableLeft', position: 'nw', icon: '/assets/custom/draw/img/zhankai.svg', attrs: {
                        '.handle': {
                            'data-tooltip-class-name': 'small',
                            'data-tooltip': '源溯',
                            'data-tooltip-position': 'right'
                        }
                    }
                });
            }

            //判断是否向右展开
            if(cellView.model.attributes.attrs.isRightOpen) {
                halo.addHandle({ name: 'myrightaction', position: 'ne', icon: '/assets/custom/draw/img/wancheng.svg' });
            }else {
                //自定义向右加载表
                halo.addHandle({
                    name: 'addTableRight', position: 'ne', icon: '/assets/custom/draw/img/zhankai.svg', attrs: {
                        '.handle': {
                            'data-tooltip-class-name': 'small',
                            'data-tooltip': '影响',
                            'data-tooltip-position': 'left'
                        }
                    }
                });
            }


            //自定义中英文切换
          /*  halo.addHandle({
                name: 'languageChange', position: 'e', icon: '/assets/custom/draw/img/englishChange.svg', attrs: {
                    '.handle': {
                        'data-tooltip-class-name': 'small',
                        'data-tooltip': '中英文切换',
                        'data-tooltip-position': 'left'
                    }
                }
            });*/

            //向左加载表事件
            halo.on('action:addTableLeft:pointerdown', function (evt) {
                evt.stopPropagation();
                cellView.model.attributes.attrs.isLeftOpen = true;

                var requestObj = {
                    objectId : cellView.model.id,
                    where : JSON.stringify(cellView.model.attributes.attrs.where),
                    forward : "before"
                };

                getTableData(requestObj);
                getRelationElements({element:cellView.model,direction:{inbound:true}},function (v) {
                    v.attributes.attrs.isLeftOpen = true;
                });
                halo.changeHandle('addTableLeft', { icon: '/assets/custom/draw/img/wancheng.svg' });
            });
            //向右加载表事件
            halo.on('action:addTableRight:pointerdown', function (evt) {
                evt.stopPropagation();
                cellView.model.attributes.attrs.isRightOpen = true;


                var requestObj = {
                    objectId : cellView.model.id,
                    where : JSON.stringify(cellView.model.attributes.attrs.where),
                    forward : "after"
                };

                getTableData(requestObj);
                getRelationElements({element:cellView.model,direction:{outbound:true}},function (v) {
                    v.attributes.attrs.isRightOpen = true;
                });
                halo.changeHandle('addTableRight', {icon: '/assets/custom/draw/img/wancheng.svg'});

            });

            //切换语言事件
/*            halo.on('action:languageChange:pointerdown', function (evt) {
                evt.stopPropagation();
//需要切换的元素
                var currentColumn = cellView.$el.find(".columnName");
//如果是英文且切换成中文(反之)
                if (cellView.model.attributes.attrs.isEnglish) {
                    $.each(currentColumn, function (i, v) {

                        var columnchname = $(this).attr("data-columnchname");
                        $(this).text(columnchname);

                        cellView.model.attributes.attrs.isEnglish = false;

                        cellView.$el.find("tspan").text(cellView.model.attributes.attrs.objectChname);
                    })

                } else {

                    $.each(currentColumn, function (i, v) {

                        var columnName = $(this).attr("data-columnName");
                        $(this).text(columnName);
                        cellView.model.attributes.attrs.isEnglish = true;
                    });

                    cellView.$el.find("tspan").text(cellView.model.attributes.attrs.tableName);
                }
//model更新
                cellView.model.attributes.attrs[".content"].html = cellView.$el.find('.content').html();
            });*/
        }
    });

    //请求表和线的数据
    function getTableData(requestObj) {
        var objectId =requestObj.objectId;
        var where =requestObj.where;
        var forward =requestObj.forward;
        $.ajax({
            url :'/rest/recordRelation/recordRelation',
            type : 'get',
            data : {objectId:objectId,where:where,forward:forward},
            dataType : 'json',
            success :function (result) {
                //遍历表对象
              $.each(result.object.vertexs,function (i,v) {
                  var object =  {
                       "objectId" : v.objectId,
                       "dsId": v.dataObj.dsId,
                       "tableName": v.dataObj.tableName,
                       "objectChname": v.dataObj.objectChname,
                       "isOpen" : {isLeftOpen : true},
                        data:v.data,
                       columns:v.columns
                   };
                  updateTable(object,false);
                 // console.log(obj);
               });

              $.each(result.object.lines,function (i, v) {
                  var line = {
                      from:v.from,
                      to:v.to,
                      lineId:v.links[0].lineId,
                      "srcColumnName":v.links[0].srcColumnName,
                      "tarColumnName":v.links[0].tarColumnName
                  };
               //   console.log(line);
                  updateLinks(line)
              });

                joint.layout.DirectedGraph.layout(graph, {
                    setLinkVertices: false,
                    marginX: 800,
                    marginY: 500,
                    rankSep : 150,
                    rankDir: "LR",
                    ranker : '500px'
                });
            }
        })
    }

    //加载表对象
    window.updateTable = function(object,isFirst) {
        var objectId = object.objectId || null; //对象id
        var columns = object.columns  || null; //表的字段名
        var isOpen = object.isOpen || null; //是否展开
        var dsId = object.dsId || null; //dsId
        var objectChname = object.objectChname ? object.objectChname : object.tableName ||null; //objectChname
        var tableName = object.tableName?object.tableName:object.objectChname  ||null; //tableName
        var data = object.data || null; //全部记录的值
        var logNumber = data.length;

        var obj = new joint.shapes.bpmn.Choreography({
            "type": "bpmn.Choreography",
            "participants": [
                 isEnglish?tableName:objectChname
            ],
            "initiatingParticipant": "Potential Buyer",
            "position": {
                "x": 800,
                "y": 500
            },
            "angle": 0,
            "embeds": "",
            "z": 1,
            "id": objectId,
            "subProcess": false,
            "attrs": {
                ".participant-rect": {
                    "fill": "ff8040",
                    "height":30
                },
                '.participant-label': {
                    'fill': '#fff'
                },
                ".sub-process": {
                    "visibility": "hidden",
                    "data-sub-process": ""
                },
                'div': {},
                '.body': {},
                'isRightOpen' : isOpen.isRightOpen,
                'isLeftOpen' : isOpen.isLeftOpen,
                 '_dsId': dsId,
                'isEnglish': true,
               'objectChname': objectChname ? objectChname : tableName,
               'tableName': tableName,
                'logs' : data.length > 1?data:null,
                'logNumber':logNumber,
                'currentLogNum' : 1
            }
        });


        var trArr = [], tr, maxField0 = 0, maxField1 = 0, showField0, showField1;
    //    var objAllFields = {};
        var whereArray = [];
        //遍历字段
        $.each(columns,function (i, v) {
            var that = v;

            //遍历字段值
            $.each(data[0],function (i,v) {
                if(that.columnName === v.columnName){

                    var whereObj = {};

                    var columnName,columnChname,currentName;
                    if(that.pk){
                        columnName = '[pk]'+ that.columnName;
                        columnChname =  that.columnChname ?'[主键]'+that.columnChname:columnName;
                        whereObj = {"srcColumnName":that.columnName,"value":v.value};
                        whereArray.push(whereObj)
                    }else {
                        columnName = that.columnName;
                        columnChname = that.columnChname ? that.columnChname :columnName;
                    }
                    isEnglish?currentName = columnName:	currentName = columnChname;
                    tr = '<tr><td class="columnName" data-columnName="' + columnName + '" data-columnChname="' + (columnChname) + '">' + currentName + '</td><td class="columnValue" data-columnName="' + that.columnName + '">' + v.value + '</td></tr>';

                    showField0 = getStringLen(currentName);
                    showField1 = getStringLen(v.value);

                    if (showField0 > maxField0) {
                        maxField0 = showField0;
                    }

                    if (showField1 > maxField1) {
                        maxField1 = showField1;
                    }
                }
            });

            trArr.push(tr);

        });

        obj.attributes.attrs.where = whereArray;
        var maxString = maxField0 + maxField1;
        var objSize = {
            'width': maxString * 7 + 80,
            'height': columns.length > 5 ? 30 * 5 + 40 : columns.length * 30 + 40
        };
        if(data.length > 1){
        	objSize.width = objSize.width>220?objSize.width:220;
            objSize.height = objSize.height + 30
        }
        console.log(objSize);
//表宽度设置
        obj.attributes.size = objSize;
        obj.attributes.attrs[".fobj"] = objSize;
        obj.attributes.attrs.div.style = objSize;
        obj.attributes.attrs[".body"] = objSize;

//table字符串
      //  var table = '<table>' + tbody + '</table>';
        var table = '<table><tbody>' + trArr.join("") + '</tbody></table>';
        var number = '<p class="totalLog">共<b>'+logNumber+'</b>条<a href="javascript:;" class="layui-icon prevTolog">&#xe603;</a><span class="layui-laypage-curr"><em>1</em></span><a href="javascript:;" class="layui-icon nextTolog">&#xe602;</a>   </p>'
        var contentStr = "";
        if(data.length > 1){
             contentStr = table+number;
        }else {
            contentStr= table
        }

//数据填充
        obj.attributes.attrs[".content"].html = contentStr;
        graph.addCells(obj);
        //第一个元素高亮
      /*  if(isFirst){
            var ele =paper.findViewByModel(obj); //cellView
            paperScroller.centerContent();
            ele.highlight(null, {
                highlighter: {
                    name: 'stroke',
                    options: {
                        padding: 6,
                        rx: 3,
                        ry: 3,
                        attrs: {
                            'stroke-width': 3,
                            stroke: '#D05454'
                        }
                    }
                }
            });
        }*/
    }

    updateTable(obj,true);
    
    //加载线
    function updateLinks(line) {
        var lineLable = line.srcColumnName +'-->'+line.tarColumnName;
        var link = new joint.shapes.app.Link({
            "source": {"id": line.from},
            "target": {"id": line.to},
            connector: {name: 'rounded'},
            "id": line.lineId,
            "attrs": {
                ".connection": {
                    "stroke": "#20C1DD",
                    "stroke-width": 2,
                    "pointerEvents": "none"
                },
                ".marker-target": {
                    "fill": "#20C1DD",
                    "stroke": "#20C1DD",
                    "d": "M 10 0 L 0 5 L 10 10 z"
                },
            }
            ,
            "labels": [
                {"position": 0.8, "attrs": {"text": {"text": lineLable}}}
            ],
            '.tool-remove': null,
        });

        graph.addCells(link);
    }

    window.changeLog = function(fields){
    	console.log(startFields);
    	console.log(fields);
    	
    	$.each(startFields,function(i,v){
    		var that = v;
    		$.each(fields,function(i,v){
    			if(that.field === v.field){
    				if(that.value !== v.value){
    					return false;
    				}
    				return true;
    			}
    		})
    	})
    	
    	if(!ArrayIsEqual(startFields,fields)){
        	var cell = graph.getCell(startId);
        	var view = paper.findViewByModel(cell);  
            var columnValueArray = view.$el.find(".columnValue");     //当前字段值数组(view)
        	var where = $.map(fields,function(v,i){
            	return {
            		srcColumnName : v.field,
            		value : v.value
            	}
            });
        	
        	cell.attributes.attrs.where  = where;
        	cell.attributes.attrs.isLeftOpen  = "";
        	cell.attributes.attrs.isRightOpen  = "";
        	cell.attributes.attrs[".content"].html = view.$el.find('.content').html(); //model中数据更新
        	$.each(where,function (i, v) { //遍历当前记录
                var that = v;
                $.each(columnValueArray,function (i, v) {  //遍历当前字段值数组(view)
                    if(that.srcColumnName === $(v).attr("data-columnname")){
                        $(v).text(that.value)
                    }
                });

            });
        	var allRelations = [];
        	  getRelationElements({element:cell,direction:{}},function (v) {
        		  allRelations.push(v)
              });
        	  $.each(allRelations,function(i,v){
        		  v.remove();
        	  })
        	  
        	  $(".joint-halo").remove();
        	 
        	  cell.position(800,500);
           	  paperScroller.centerContent();
           	 // graph.clear()
    	}
    
    }
    
    function ArrayIsEqual(array1,array2) {

        for(var i = 0;i<array1.length;i++){
            for(var j =0;j<array2.length;j++){
                if(array1[i].field === array2[j].field){
                    if(array1[i].value !== array2[j].value){
                        return false;
                    }
                }
            }

        }
        return true;
    }
    
})();

